﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ParkingLot.Utility.LogHelps;

namespace ParkingLot.Utility.SocketHelp
{
    /*本机一个端口,发送方一个端口*/

    public class SendHelp
    {
        //private static UdpClient udpClient;

        //创建用于发送的UDP端口号
        private static UdpClient CreateUdpClient()
        {
            UdpClient udpClient = null;
            //设置发送端口
            Random r = new Random(DateTime.Now.Millisecond);
            bool isSuccessSetPort = false;
            while (!isSuccessSetPort)
            {
                //源端口  目的端口
                int localPort = r.Next(0, 1000) % 1000 + 1000;
                try
                {
                    udpClient = new UdpClient(localPort);
                    isSuccessSetPort = true;
                }
                catch (Exception e)
                {
                    localPort = r.Next() % 1000 + 1000;
                }
            }
            //是否发送或接受广播
            udpClient.EnableBroadcast = true;
            //自发自收
            udpClient.MulticastLoopback = true;

            return udpClient;
        }

        #region Instance

        private static SendHelp m_Instance;



        public static SendHelp Instance
        {
            get
            {
                if (m_Instance == null)
                    m_Instance = new SendHelp();
                return m_Instance;
            }
        }

        #endregion

        /// <summary>
        /// 发送数据包到某个IP地址的某个端口
        /// </summary>
        /// <param name="ipAddress">IP地址</param>
        /// <param name="port">端口</param>
        /// <param name="data">数据</param>
        public static void StartSend(string ipAddress, int port, byte[] data)
        {
            //写日志记录数据发送情况
            StringBuilder sbError = new StringBuilder();

            UdpClient udpClient = CreateUdpClient();
            using (udpClient)
            {
                try
                {
                    udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(ipAddress), port));

                }
                catch (Exception ex)
                {
                    sbError.AppendLine(DateTime.Now.ToString() + ex.Message);
                    LogHelp.AddLog(new LogEncity(ex));
                }
                finally
                {
                    udpClient.Close();
                }
            }


        }


        /// <summary>
        /// 发送数据包到某个IP地址的某个端口
        /// </summary>
        /// <param name="ipAddress">IP地址</param>
        /// <param name="port">端口</param>
        /// <param name="data">数据</param>
        public static void StartFirmSend(string ipAddress, int port, byte[] data)
        {
            //写日志记录数据发送情况
            StringBuilder sbError = new StringBuilder();
            UdpClient udpClient = CreateUdpClient();
            Task task = new Task(() =>
              {
                  using (udpClient)
                  {
                      try
                      {
                          int haveSendBytes = udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(ipAddress), port));
                          if (data.Length != haveSendBytes)
                          {

                          }
                          for (int i = 0; i < 5; i++)
                          {
                              Thread.Sleep(200);
                              haveSendBytes = udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(ipAddress), port));
                              if (data.Length != haveSendBytes)
                              {

                              }
                          }
                      }
                      catch (Exception ex)
                      {
                          sbError.AppendLine(DateTime.Now.ToString() + ex.Message);
                          LogHelp.AddLog(new LogEncity(ex));
                      }
                      finally
                      {
                          udpClient.Close();
                      }
                  }
              });
            task.Start();
        }

    }
}
